from base64 import b32encode, b32decode
from binascii import hexlify, unhexlify

MAGNET_PREFIX = "magnet:?xt=urn:btih:"

def HashToMagnet(infohash, asHex = False):
    if asHex:
        infohash = unhexlify(infohash)
    magnet = b32encode(infohash)
    return magnet
    
def MagnetToHash(magnet, asHex = False):
    hashval = b32decode(magnet)
    if asHex:
        hashval = hexlify(hashval)
    return hashval

def getArgument(magnetURI, argument):
    # TODO: some arguments are allowed more than once
    argument += '='
    pos = magnetURI.find('?'+argument)
    if pos < 0:
        pos = magnetURI.find('&'+argument)
    if pos > 0:
        pos += len(argument)+1
        stoppos = magnetURI.find('&', pos)
        if stoppos < 0:
            return magnetURI[pos:]
        return magnetURI[pos:stoppos]
    return ""

def getHash(magnetURI, asHex = False):
    xt = getArgument(magnetURI, "xt")
    if xt[:9] != "urn:btih:":
        return False
    return MagnetToHash(xt[9:], asHex)
